﻿using NLua;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TextAutoEdit
{
    internal class MLuaEvn
    {
        public static readonly string CSEvnFile = AppDomain.CurrentDomain.BaseDirectory + "CSEvn.lua";
        public static readonly string LuaFuncFile = AppDomain.CurrentDomain.BaseDirectory + "funcs.lua";

        public static async Task<bool> InitAsync(Assembly assembly)
        {
            return await Task.Run(() =>
            {
                if (!File.Exists(CSEvnFile))
                {
                    FileStream fs = File.Open(CSEvnFile, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs);
                    foreach (var type in CS2Lua.GetTypes(assembly))
                    {
                        sw.WriteLine(CS2Lua.GetLuaScipt(type));
                    }
                    sw.Close();
                    fs.Close();
                }

                if (!File.Exists(LuaFuncFile))
                {
                    File.Create(LuaFuncFile).Close();
                }
                return true;
            });
        }

        //public static Task<bool> LoadAsync()
        //{
        //    string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.lua");
        //    for (int i = 0; i < files.Length; i++)
        //    {
        //        string nameNoEx = Path.GetFileNameWithoutExtension(files[i]);
        //        lua.DoFile(files[i]);
        //    }
        //    return true;
        //}

        public static Lua GetLua()
        {
            Lua lua = new Lua();
            LoadFile(lua);
            return lua;
        }

        public static void LoadFile(Lua lua)
        {
            lua.DoFile(CSEvnFile);
            lua.DoFile(LuaFuncFile);
            lua.State.Encoding = Encoding.UTF8;

            lua.RegisterFunction("CSLog", typeof(MLog).GetMethod("Log"));
            lua.RegisterFunction("CSDefaultDoString", typeof(MLua).GetMethod("DoString"));
            lua.RegisterFunction("CSSetTB", MainForm.Instance, MainForm.Instance.GetType().GetMethod("SetTBContent"));
        }
    }
}
